-- Leviathan (c) v.v.balashoff
local Class = require('leviathan/Class')

local HoverSystem = Class:derive('UIHoverSystem')

function HoverSystem:new(domain)
    self.name = 'HoverSystem'
    self.domain = domain
end

function HoverSystem:update(dt)
    local inputDomain = world:getDomain('Input')
    -- update hover components
    inputComps = self.domain.components['Input']
    for _, c in pairs(inputComps) do
        if c.entity.enabled and c.enabled then
            if c.id == 'MouseHoverComponent' then
                self:updateMouseHover(c)
            end
        end
    end
end

function HoverSystem:updateMouseHover(c)
    local mx, my = love.mouse.getPosition()
    local bufferX = c.entity.domain.buffer.worldX
    local bufferY = c.entity.domain.buffer.worldY
    local worldX = c.entity.worldX + bufferX
    local worldY = c.entity.worldY + bufferY
    local hovered = false
    if (mx >= worldX) then
        if (my >= worldY) then
            local width = c.entity.width
            local height = c.entity.height
            if (mx <= worldX + width) then
                if (my <= worldY + height) then
                    hovered = true
                end
            end
        end
    end
    if not c.hovered == hovered then
        c.hovered = hovered
        if hovered then
            if c.inside then
                c:inside()
            end
        else
            if c.outside then
                c:outside()
            end
        end
    end
end

return HoverSystem
